package cn.pindao.t_upgrade_plugin

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.Registrar
import java.io.File

/** TUpgradePlugin */
public class TUpgradePlugin() : FlutterPlugin, MethodCallHandler, ActivityAware,
        PluginRegistry.ActivityResultListener {
    private lateinit var channel: MethodChannel
    private lateinit var activity: Activity
    private val REQUEST_PERMISSION_CODE = 100001
    private lateinit var filePatch: String

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "tea_upgrade_plugin")
        channel.setMethodCallHandler(this)
    }

    companion object {
        @JvmStatic
        fun registerWith(registrar: Registrar) {
            val channel = MethodChannel(registrar.messenger(), "t_upgrade_plugin")
            channel.setMethodCallHandler(TUpgradePlugin())
        }
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            "getPlatformVersion" -> {
                result.success("Android ${android.os.Build.VERSION.RELEASE}")
            }
            "installApk" -> {
                val map = call.arguments as Map<String, String>
                filePatch = map["filePatch"].toString()
                update()
            }
            else -> {
                result.notImplemented()
            }
        }
    }

    fun update() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            UpdateUtil.installApp(activity, File(filePatch))
        } else {
            val hasInstallPermission = activity.packageManager.canRequestPackageInstalls()
            if (hasInstallPermission) {
                UpdateUtil.installApp(activity, File(filePatch))
            } else {
                checkPermission()
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun checkPermission() {
        val packageURI = Uri.parse("package:${activity.packageName}")
        val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
        activity.startActivityForResult(intent, REQUEST_PERMISSION_CODE)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_PERMISSION_CODE) {
            val hasInstallPermission = activity.packageManager.canRequestPackageInstalls()
            if (hasInstallPermission) {
                UpdateUtil.installApp(activity, File(filePatch))
            } else {
                Toast.makeText(activity, "安装失败，请前往设置中打开安装权限", Toast.LENGTH_LONG).show()
            }
            return true
        }
        return false
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    override fun onDetachedFromActivity() {
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {

    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        binding.addActivityResultListener(this)
        activity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {
    }
}
